
import 'package:shortmovieapp/Common.dart';
import 'package:json_annotation/json_annotation.dart';
import 'dart:convert';

import 'package:shortmovieapp/data/viewData.dart';

part 'localData.g.dart';

//运行命令：dart run build_runner build

@JsonSerializable()
class LocalData {
  
  @JsonKey(includeIfNull: false)
  List<MovieItemData>? faviorites;

  LocalData({this.faviorites});
  
  // 命名构造函数，用于从JSON创建对象
  factory LocalData.fromJson(Map<String, dynamic> json) => _$LocalDataFromJson(json);

  // 将对象转换为JSON
  Map<String, dynamic> toJson() => _$LocalDataToJson(this);

  void UpdateFaviorites(List<MovieItemData> value){
      this.faviorites = value;
      writeLocalData();
  }
  
  static LocalData readLocalData(){
      Debug.log("read local data:");
      //LocalData newData = LocalData();
      //var data = RequestServerController().getSearchMovies("测试");
      //newData.UpdateFaviorites(data);

      String jsonString = "{}";

      if(jsonString == null || jsonString.isEmpty){
        return LocalData();
      }
       var map =  json.decode(jsonString);
       var res = LocalData.fromJson(map);
       Debug.log("read data:${res.faviorites?.length}");
       return res;
  }

  void writeLocalData(){
      String userJson = json.encode(this.toJson());

      Debug.log("write local data:$userJson");
  }
}

@JsonSerializable(includeIfNull: false)
class MovieItemData {
  
  @JsonKey()
  int movieId;
  @JsonKey()
  String title = "";
  @JsonKey()
  String iconUrl = "";
  @JsonKey()
  int watchTimes;
  @JsonKey()
  int episodeCount;
  @JsonKey()
  String type;
  @JsonKey()
  String desc;

  String get typeName => MovieType2String(parseMovieType(type));
  
  MovieItemData(this.movieId, this.title, this.iconUrl, this.episodeCount,
      this.type, this.watchTimes,this.desc);

        // 命名构造函数，用于从JSON创建对象
  factory MovieItemData.fromJson(Map<String, dynamic> json) => _$MovieItemDataFromJson(json);
  // 将对象转换为JSON
  Map<String, dynamic> toJson() => _$MovieItemDataToJson(this);

  factory MovieItemData.fromJsonString(String jsonString)=>
       _$MovieItemDataFromJson(json.decode(jsonString));
  String toJsonString() =>  json.encode(toJson());

  @override 
  String toString() {
    return "[movieId:$movieId,title:$title,iconUrl:$iconUrl,type:$type,episodeCount:$episodeCount,watchTimes:$watchTimes]";
  }
}